/**
 * 系统设置页面脚本
 */
document.addEventListener('DOMContentLoaded', function() {
    // 初始化选项卡切换功能
    initTabSwitching();
    
    // 初始化表单提交事件
    initFormSubmissions();
    
    // 初始化文件上传预览
    initFileUploadPreview();
    
    // 加载系统配置数据
    loadSystemConfig();
    
    // 初始化角色与权限管理
    initRolesAndPermissions();
    
    // 初始化系统日志功能
    initSystemLogs();
    
    // 初始化备份功能
    initBackupSystem();
});

/**
 * 初始化选项卡切换功能
 */
function initTabSwitching() {
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            // 移除所有选项卡的活动状态
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabContents.forEach(content => content.classList.remove('active'));
            
            // 设置点击的选项卡为活动状态
            button.classList.add('active');
            const targetId = button.getAttribute('data-target');
            document.getElementById(targetId).classList.add('active');
            
            // 保存用户选择的选项卡到会话存储
            sessionStorage.setItem('activeSettingsTab', targetId);
        });
    });
    
    // 从会话存储中恢复上次选择的选项卡
    const activeTab = sessionStorage.getItem('activeSettingsTab');
    if (activeTab) {
        const activeButton = document.querySelector(`.tab-button[data-target="${activeTab}"]`);
        if (activeButton) {
            activeButton.click();
        }
    }
}

/**
 * 初始化表单提交事件
 */
function initFormSubmissions() {
    // 通用设置表单
    const generalSettingsForm = document.getElementById('generalSettingsForm');
    if (generalSettingsForm) {
        generalSettingsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveGeneralSettings();
        });
    }
    
    // 安全设置表单
    const securitySettingsForm = document.getElementById('securitySettingsForm');
    if (securitySettingsForm) {
        securitySettingsForm.addEventListener('submit', function(e) {
            e.preventDefault();
            saveSecuritySettings();
        });
    }
    
    // 日志筛选表单
    const logsFilterForm = document.getElementById('logsFilterForm');
    if (logsFilterForm) {
        logsFilterForm.addEventListener('submit', function(e) {
            e.preventDefault();
            filterLogs();
        });
    }
}

/**
 * 初始化文件上传预览
 */
function initFileUploadPreview() {
    const logoFileInput = document.getElementById('logoFile');
    const logoPreview = document.getElementById('logoPreview');
    
    if (logoFileInput && logoPreview) {
        logoFileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const fileName = file.name;
                logoPreview.querySelector('.file-name').textContent = fileName;
                
                // 如果是图片文件则预览
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        // 创建或更新预览图片
                        let img = logoPreview.querySelector('img');
                        if (!img) {
                            img = document.createElement('img');
                            img.style.height = '40px';
                            img.style.width = 'auto';
                            logoPreview.querySelector('span[data-icon]').style.display = 'none';
                            logoPreview.appendChild(img);
                        }
                        img.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            }
        });
    }
}

/**
 * 加载系统配置数据
 */
function loadSystemConfig() {
    // 模拟从API获取配置数据
    // 实际应用中应该调用后端API
    simulateApiCall('/api/admin/configs', 'GET')
        .then(data => {
            // 填充通用设置表单
            fillGeneralSettingsForm(data);
            
            // 填充安全设置表单
            fillSecuritySettingsForm(data);
        })
        .catch(error => {
            showNotification('错误', '加载系统配置失败: ' + error.message, 'error');
        });
}

/**
 * 填充通用设置表单
 * @param {Object} config - 系统配置对象
 */
function fillGeneralSettingsForm(config) {
    const form = document.getElementById('generalSettingsForm');
    if (form) {
        form.elements.systemName.value = config.systemName || '';
        form.elements.allowedFileTypes.value = config.allowedFileTypes || '';
        form.elements.maxFileSize.value = config.maxFileSize ? (config.maxFileSize / 1048576) : ''; // 转换为MB
    }
}

/**
 * 填充安全设置表单
 * @param {Object} config - 系统配置对象
 */
function fillSecuritySettingsForm(config) {
    const form = document.getElementById('securitySettingsForm');
    if (form) {
        form.elements.passwordExpireDays.value = config.passwordExpireDays || '';
        form.elements.maxLoginAttempts.value = config.maxLoginAttempts || '';
        form.elements.sessionTimeoutMinutes.value = config.sessionTimeoutMinutes || '';
        form.elements.minPasswordLength.value = config.minPasswordLength || '';
        
        // 密码复杂度要求
        if (config.passwordPolicy) {
            form.elements.requireUppercase.checked = config.passwordPolicy.requireUppercase || false;
            form.elements.requireLowercase.checked = config.passwordPolicy.requireLowercase || false;
            form.elements.requireNumbers.checked = config.passwordPolicy.requireNumbers || false;
            form.elements.requireSpecialChars.checked = config.passwordPolicy.requireSpecialChars || false;
        }
    }
}

/**
 * 保存通用设置
 */
function saveGeneralSettings() {
    const form = document.getElementById('generalSettingsForm');
    if (!form) return;
    
    const formData = new FormData(form);
    const data = {
        systemName: formData.get('systemName'),
        allowedFileTypes: formData.get('allowedFileTypes'),
        maxFileSize: Number(formData.get('maxFileSize')) * 1048576 // 转为字节
    };
    
    // 如果有上传的Logo文件
    const logoFile = formData.get('logoFile');
    if (logoFile && logoFile.size > 0) {
        // 实际应用中，应使用FormData进行文件上传
        console.log('Logo file selected:', logoFile.name);
    }
    
    // 模拟保存操作
    simulateApiCall('/api/admin/configs', 'PUT', data)
        .then(response => {
            showNotification('成功', '通用设置保存成功', 'success');
        })
        .catch(error => {
            showNotification('错误', '保存失败: ' + error.message, 'error');
        });
}

/**
 * 保存安全设置
 */
function saveSecuritySettings() {
    const form = document.getElementById('securitySettingsForm');
    if (!form) return;
    
    const data = {
        passwordExpireDays: Number(form.elements.passwordExpireDays.value),
        maxLoginAttempts: Number(form.elements.maxLoginAttempts.value),
        sessionTimeoutMinutes: Number(form.elements.sessionTimeoutMinutes.value),
        minPasswordLength: Number(form.elements.minPasswordLength.value),
        passwordPolicy: {
            requireUppercase: form.elements.requireUppercase.checked,
            requireLowercase: form.elements.requireLowercase.checked,
            requireNumbers: form.elements.requireNumbers.checked,
            requireSpecialChars: form.elements.requireSpecialChars.checked
        }
    };
    
    // 模拟保存操作
    simulateApiCall('/api/admin/security-settings', 'PUT', data)
        .then(response => {
            showNotification('成功', '安全设置保存成功', 'success');
        })
        .catch(error => {
            showNotification('错误', '保存失败: ' + error.message, 'error');
        });
}

/**
 * 初始化角色与权限管理
 */
function initRolesAndPermissions() {
    // 加载角色列表
    loadRolesList();
    
    // 角色项点击事件
    document.getElementById('rolesList').addEventListener('click', function(e) {
        if (e.target.tagName === 'LI') {
            // 移除所有项的活动状态
            this.querySelectorAll('li').forEach(li => li.classList.remove('active'));
            // 设置点击的项为活动状态
            e.target.classList.add('active');
            // 加载角色权限
            loadRolePermissions(e.target.textContent);
        }
    });
    
    // 添加角色按钮点击事件
    document.getElementById('addRoleBtn').addEventListener('click', function() {
        showAddRoleDialog();
    });
    
    // 编辑角色按钮点击事件
    document.getElementById('editRoleBtn').addEventListener('click', function() {
        const currentRole = document.getElementById('currentRoleName').textContent;
        showEditRoleDialog(currentRole);
    });
    
    // 删除角色按钮点击事件
    document.getElementById('deleteRoleBtn').addEventListener('click', function() {
        const currentRole = document.getElementById('currentRoleName').textContent;
        showDeleteRoleConfirmation(currentRole);
    });
}

/**
 * 加载角色列表
 */
function loadRolesList() {
    // 模拟从API获取角色列表
    simulateApiCall('/api/admin/roles', 'GET')
        .then(data => {
            // 此处用于实际实现
            // 目前使用默认数据，在实际应用中应替换为API返回数据
        })
        .catch(error => {
            showNotification('错误', '加载角色列表失败: ' + error.message, 'error');
        });
}

/**
 * 加载角色权限
 * @param {string} roleName - 角色名称
 */
function loadRolePermissions(roleName) {
    document.getElementById('currentRoleName').textContent = roleName;
    
    // 模拟从API获取角色权限
    simulateApiCall(`/api/admin/roles/${roleName}/permissions`, 'GET')
        .then(data => {
            // 此处用于实际实现
            // 目前使用默认数据，在实际应用中应替换为API返回数据
            // 示例: updatePermissionsList(data.permissions);
        })
        .catch(error => {
            showNotification('错误', '加载权限列表失败: ' + error.message, 'error');
        });
}

/**
 * 初始化系统日志功能
 */
function initSystemLogs() {
    // 加载系统日志
    loadSystemLogs();
    
    // 分页事件处理
    const pagination = document.getElementById('logsPagination');
    if (pagination) {
        const prevBtn = pagination.querySelector('.page-btn:first-child');
        const nextBtn = pagination.querySelector('.page-btn:last-child');
        
        prevBtn.addEventListener('click', function() {
            if (!this.disabled) {
                currentPage = Math.max(1, currentPage - 1);
                loadSystemLogs(currentPage);
            }
        });
        
        nextBtn.addEventListener('click', function() {
            if (!this.disabled) {
                currentPage += 1;
                loadSystemLogs(currentPage);
            }
        });
    }
}

// 当前日志页码
let currentPage = 1;

/**
 * 加载系统日志
 * @param {number} page - 页码
 */
function loadSystemLogs(page = 1) {
    const formData = new FormData(document.getElementById('logsFilterForm'));
    const params = {
        page: page - 1, // 后端通常从0开始计数
        size: 20,
        startDate: formData.get('startDate') || '',
        endDate: formData.get('endDate') || '',
        username: formData.get('username') || '',
        operation: formData.get('operation') || ''
    };
    
    // 模拟从API获取日志数据
    simulateApiCall('/api/admin/logs', 'GET', null, params)
        .then(data => {
            updateLogsTable(data);
            updatePagination(data, page);
        })
        .catch(error => {
            showNotification('错误', '加载系统日志失败: ' + error.message, 'error');
        });
}

/**
 * 更新日志表格
 * @param {Object} data - 日志数据
 */
function updateLogsTable(data) {
    const table = document.getElementById('logsList');
    if (!table) return;
    
    // 清空现有内容
    table.innerHTML = '';
    
    if (data.content && data.content.length > 0) {
        data.content.forEach(log => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${log.id}</td>
                <td>${log.username}</td>
                <td>${translateOperation(log.operation)}</td>
                <td>${log.description}</td>
                <td>${log.ip}</td>
                <td>${formatDate(log.createTime)}</td>
            `;
            table.appendChild(row);
        });
    } else {
        const row = document.createElement('tr');
        row.className = 'placeholder-row';
        row.innerHTML = '<td colspan="6">没有找到匹配的日志记录</td>';
        table.appendChild(row);
    }
}

/**
 * 更新分页信息
 * @param {Object} data - 分页数据
 * @param {number} currentPage - 当前页码
 */
function updatePagination(data, currentPage) {
    const pagination = document.getElementById('logsPagination');
    if (!pagination) return;
    
    const prevBtn = pagination.querySelector('.page-btn:first-child');
    const nextBtn = pagination.querySelector('.page-btn:last-child');
    const pageInfo = pagination.querySelector('.page-info');
    
    prevBtn.disabled = currentPage <= 1;
    nextBtn.disabled = currentPage >= data.totalPages;
    pageInfo.textContent = `第${currentPage}页，共${data.totalPages}页`;
}

/**
 * 翻译操作类型为中文
 * @param {string} operation - 操作类型
 * @returns {string} 中文操作类型
 */
function translateOperation(operation) {
    const translations = {
        'USER_CREATE': '创建用户',
        'USER_UPDATE': '更新用户',
        'USER_DELETE': '删除用户',
        'LOGIN': '用户登录',
        'LOGOUT': '用户登出',
        'PRESCRIPTION_CREATE': '创建处方',
        'PATIENT_CREATE': '创建患者',
        'SYSTEM_CONFIG': '系统配置'
    };
    
    return translations[operation] || operation;
}

/**
 * 格式化日期时间
 * @param {number} timestamp - 时间戳
 * @returns {string} 格式化的日期时间字符串
 */
function formatDate(timestamp) {
    const date = new Date(timestamp);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 根据表单筛选日志
 */
function filterLogs() {
    currentPage = 1; // 重置为第一页
    loadSystemLogs(currentPage);
}

/**
 * 初始化备份系统
 */
function initBackupSystem() {
    // 加载备份历史
    loadBackupHistory();
    
    // 创建备份按钮点击事件
    document.getElementById('createBackupBtn').addEventListener('click', function() {
        createSystemBackup();
    });
}

/**
 * 加载备份历史
 */
function loadBackupHistory() {
    // 模拟从API获取备份历史
    simulateApiCall('/api/admin/backups', 'GET')
        .then(data => {
            updateBackupTable(data);
        })
        .catch(error => {
            showNotification('错误', '加载备份历史失败: ' + error.message, 'error');
        });
}

/**
 * 更新备份历史表格
 * @param {Array} backups - 备份记录数组
 */
function updateBackupTable(backups) {
    const table = document.getElementById('backupList');
    if (!table) return;
    
    // 清空现有内容
    table.innerHTML = '';
    
    if (backups && backups.length > 0) {
        backups.forEach(backup => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${backup.backupId}</td>
                <td>${formatDate(backup.backupTime)}</td>
                <td>${formatFileSize(backup.backupSize)}</td>
                <td>
                    <button class="btn btn-sm btn-outline restore-backup" data-id="${backup.backupId}">
                        <span data-icon="restore"></span> 恢复
                    </button>
                    <button class="btn btn-sm btn-secondary download-backup" data-path="${backup.backupPath}">
                        <span data-icon="download"></span> 下载
                    </button>
                    <button class="btn btn-sm btn-danger delete-backup" data-id="${backup.backupId}">
                        <span data-icon="delete"></span> 删除
                    </button>
                </td>
            `;
            table.appendChild(row);
        });
        
        // 添加恢复备份事件
        table.querySelectorAll('.restore-backup').forEach(btn => {
            btn.addEventListener('click', function() {
                const backupId = this.getAttribute('data-id');
                showRestoreConfirmation(backupId);
            });
        });
        
        // 添加下载备份事件
        table.querySelectorAll('.download-backup').forEach(btn => {
            btn.addEventListener('click', function() {
                const backupPath = this.getAttribute('data-path');
                downloadBackup(backupPath);
            });
        });
        
        // 添加删除备份事件
        table.querySelectorAll('.delete-backup').forEach(btn => {
            btn.addEventListener('click', function() {
                const backupId = this.getAttribute('data-id');
                showDeleteBackupConfirmation(backupId);
            });
        });
    } else {
        const row = document.createElement('tr');
        row.className = 'placeholder-row';
        row.innerHTML = '<td colspan="4">尚未创建任何备份</td>';
        table.appendChild(row);
    }
}

/**
 * 创建系统备份
 */
function createSystemBackup() {
    // 显示正在备份的提示
    showNotification('请稍候', '系统备份中...', 'info');
    
    // 模拟API调用创建备份
    simulateApiCall('/api/admin/backup', 'POST')
        .then(response => {
            showNotification('成功', '系统备份已成功创建', 'success');
            // 重新加载备份历史
            loadBackupHistory();
        })
        .catch(error => {
            showNotification('错误', '创建备份失败: ' + error.message, 'error');
        });
}

/**
 * 显示恢复备份确认对话框
 * @param {string} backupId - 备份ID
 */
function showRestoreConfirmation(backupId) {
    if (confirm(`您确定要恢复到备份 ${backupId} 吗？\n此操作将覆盖当前数据，且无法撤销。`)) {
        restoreFromBackup(backupId);
    }
}

/**
 * 从备份恢复
 * @param {string} backupId - 备份ID
 */
function restoreFromBackup(backupId) {
    // 显示正在恢复的提示
    showNotification('请稍候', '正在从备份恢复系统...', 'info');
    
    // 模拟API调用恢复备份
    simulateApiCall(`/api/admin/restore/${backupId}`, 'POST')
        .then(response => {
            showNotification('成功', '系统已成功从备份恢复', 'success');
        })
        .catch(error => {
            showNotification('错误', '恢复备份失败: ' + error.message, 'error');
        });
}

/**
 * 显示删除备份确认对话框
 * @param {string} backupId - 备份ID
 */
function showDeleteBackupConfirmation(backupId) {
    if (confirm(`您确定要删除备份 ${backupId} 吗？`)) {
        deleteBackup(backupId);
    }
}

/**
 * 删除备份
 * @param {string} backupId - 备份ID
 */
function deleteBackup(backupId) {
    // 模拟API调用删除备份
    simulateApiCall(`/api/admin/backups/${backupId}`, 'DELETE')
        .then(response => {
            showNotification('成功', '备份已成功删除', 'success');
            // 重新加载备份历史
            loadBackupHistory();
        })
        .catch(error => {
            showNotification('错误', '删除备份失败: ' + error.message, 'error');
        });
}

/**
 * 下载备份
 * @param {string} backupPath - 备份文件路径
 */
function downloadBackup(backupPath) {
    // 在实际应用中，这里应该是一个实际的下载链接
    console.log('下载备份:', backupPath);
    
    // 模拟下载过程
    showNotification('信息', '备份文件下载已开始', 'info');
}

/**
 * 格式化文件大小
 * @param {number} bytes - 字节数
 * @returns {string} 格式化后的大小
 */
function formatFileSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
    else if (bytes < 1073741824) return (bytes / 1048576).toFixed(1) + ' MB';
    else return (bytes / 1073741824).toFixed(1) + ' GB';
}

/**
 * 显示通知信息
 * @param {string} title - 通知标题
 * @param {string} message - 通知内容
 * @param {string} type - 通知类型（success, error, info, warning）
 */
function showNotification(title, message, type = 'info') {
    // 此处为模拟实现，实际应用中应该使用项目中现有的通知组件
    console.log(`[${type.toUpperCase()}] ${title}: ${message}`);
    
    // 简单的弹窗实现
    if (type === 'error') {
        alert(`错误: ${message}`);
    } else if (type === 'success') {
        // 可以使用自定义通知组件，这里简化处理
        const event = new CustomEvent('showToast', { 
            detail: { message: message, type: type }
        });
        document.dispatchEvent(event);
    }
}

/**
 * 模拟API调用
 * @param {string} url - API地址
 * @param {string} method - 请求方法
 * @param {Object} data - 请求数据
 * @param {Object} params - URL参数
 * @returns {Promise} Promise对象
 */
function simulateApiCall(url, method, data = null, params = null) {
    console.log(`模拟API调用: ${method} ${url}`);
    console.log('数据:', data);
    console.log('参数:', params);
    
    return new Promise((resolve, reject) => {
        // 模拟网络延迟
        setTimeout(() => {
            // 根据URL返回模拟数据
            if (url === '/api/admin/configs' && method === 'GET') {
                resolve({
                    systemName: '智能医疗诊断助手',
                    version: '1.0.0',
                    maxLoginAttempts: 5,
                    passwordExpireDays: 90,
                    sessionTimeoutMinutes: 30,
                    allowedFileTypes: 'jpg,jpeg,png,pdf,doc,docx',
                    maxFileSize: 10485760,
                    minPasswordLength: 8,
                    passwordPolicy: {
                        requireUppercase: true,
                        requireLowercase: true,
                        requireNumbers: true,
                        requireSpecialChars: false
                    }
                });
            } 
            else if (url === '/api/admin/configs' && method === 'PUT') {
                resolve({ success: true, message: '配置已更新' });
            }
            else if (url === '/api/admin/security-settings' && method === 'PUT') {
                resolve({ success: true, message: '安全设置已更新' });
            }
            else if (url === '/api/admin/roles' && method === 'GET') {
                resolve([
                    {
                        id: 1,
                        name: '管理员',
                        description: '系统管理员',
                        permissions: [
                            { id: 1, name: 'USER_MANAGE', description: '用户管理权限' },
                            { id: 2, name: 'ROLE_MANAGE', description: '角色管理权限' }
                        ]
                    },
                    {
                        id: 2,
                        name: '医生',
                        description: '医生角色',
                        permissions: [
                            { id: 3, name: 'PATIENT_VIEW', description: '查看患者信息权限' },
                            { id: 4, name: 'PRESCRIPTION_MANAGE', description: '处方管理权限' }
                        ]
                    }
                ]);
            }
            else if (url.includes('/api/admin/roles/') && url.includes('/permissions')) {
                resolve([
                    { id: 1, name: 'USER_MANAGE', description: '用户管理权限' },
                    { id: 2, name: 'ROLE_MANAGE', description: '角色管理权限' }
                ]);
            }
            else if (url === '/api/admin/logs') {
                resolve({
                    content: [
                        {
                            id: 1,
                            userId: 1,
                            username: 'admin',
                            operation: 'USER_CREATE',
                            description: '创建用户: doctor1',
                            ip: '192.168.1.100',
                            createTime: Date.now() - 86400000
                        },
                        {
                            id: 2,
                            userId: 2,
                            username: 'doctor1',
                            operation: 'PRESCRIPTION_CREATE',
                            description: '创建处方: ID=1, 患者=张三',
                            ip: '192.168.1.101',
                            createTime: Date.now() - 3600000
                        }
                    ],
                    totalElements: 100,
                    totalPages: 5,
                    size: 20,
                    number: params ? params.page : 0
                });
            }
            else if (url === '/api/admin/backups') {
                resolve([
                    {
                        backupId: 'backup_20230615_120000',
                        backupTime: Date.now() - 86400000,
                        backupSize: 15728640,
                        backupPath: '/backups/backup_20230615_120000.zip'
                    },
                    {
                        backupId: 'backup_20230610_120000',
                        backupTime: Date.now() - 432000000,
                        backupSize: 14728640,
                        backupPath: '/backups/backup_20230610_120000.zip'
                    }
                ]);
            }
            else if (url === '/api/admin/backup' && method === 'POST') {
                resolve({
                    backupId: `backup_${new Date().toISOString().substring(0, 10).replace(/-/g, '')}_${new Date().getHours()}${new Date().getMinutes()}${new Date().getSeconds()}`,
                    backupTime: Date.now(),
                    backupSize: 16728640,
                    backupPath: `/backups/backup_${new Date().toISOString().substring(0, 10).replace(/-/g, '')}_${new Date().getHours()}${new Date().getMinutes()}${new Date().getSeconds()}.zip`
                });
            }
            else if (url.includes('/api/admin/restore/') && method === 'POST') {
                resolve({
                    backupId: url.split('/').pop(),
                    restoreTime: Date.now(),
                    status: 'SUCCESS'
                });
            }
            else if (url.includes('/api/admin/backups/') && method === 'DELETE') {
                resolve({ success: true });
            }
            else {
                reject(new Error('未知API或方法'));
            }
        }, 300);
    });
}